package cn.nfwx.tv.controller;

import android.app.Activity;
import android.support.v4.app.FragmentManager;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;

import cn.nfwx.tv.callback.ResponseCallback;
import cn.nfwx.tv.callback.ResponseWithFailListener;
import cn.nfwx.tv.fragment.MovementFragment;
import cn.nfwx.tv.helper.DialogFragmentHelper;
import cn.nfwx.tv.manager.AdvertiseManager;
import cn.nfwx.tv.model.Movement;
import cn.nfwx.tv.model.Result;

public class MovementController {

    private boolean isAppUpdate = false;

    private static MovementController instance;

    public static MovementController getInstance() {
        if (instance == null) {
            synchronized (MovementController.class) {
                if (instance == null) {
                    instance = new MovementController();
                }
            }
        }
        return instance;
    }

    public void setAppUpdate(boolean appUpdate) {
        isAppUpdate = appUpdate;
    }

    public void dimissMent(FragmentManager fragmentManager) {
        DialogFragmentHelper.removeFragment(fragmentManager, "ment");
    }

    public void loadData(final Activity activity, final FragmentManager fragmentManager) {
        AdvertiseManager.requestIjkMovement(activity, new ResponseWithFailListener<String>() {
            @Override
            public void onResponse(String requestTag, final String response) {
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (!TextUtils.isEmpty(response)) {
                            if (!fragmentManager.isDestroyed() && !isAppUpdate) {
                                Result<Movement> result = JSON.parseObject(response, new TypeReference<Result<Movement>>() {
                                }.getType());
                                if (!TextUtils.isEmpty(result.getData().getUrl())) {
                                    MovementFragment movementFragment = MovementFragment.newInstance(result.getData());
                                    DialogFragmentHelper.showDialogFragment(fragmentManager, movementFragment, "ment");
                                }
                            }
                        }
                    }
                });
            }

            @Override
            public void onError(String requestTag, Throwable t) {

            }

            @Override
            public void onFinish() {

            }

            @Override
            public void onFail(String requestTag, String response) {

            }
        });
    }


}
